<script lang="ts" setup>
import type { Message } from '#/api/openapi/api';

import { computed, ref, watch } from 'vue';

import { Close, Delete } from '@icon-park/vue-next';
import { message } from 'ant-design-vue';

import { client } from '#/api/core/client';
import Button from '#/components/fluentui/Button.vue';
import Dialog from '#/components/fluentui/Dialog.vue';
import DialogBody from '#/components/fluentui/DialogBody.vue';

type MessageItem = Message;
// Props
interface Props {
  modelValue?: boolean;
  currentUploadItemId?: string;
  currentShareCode?: string;
  currentEditToken?: string;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  currentUploadItemId: undefined,
  currentShareCode: undefined,
  currentEditToken: undefined,
});

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
}>();

// 响应式状态
const isVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
});

const messageList = ref<MessageItem[]>([]);
const newMessageContent = ref('');
const pullMessages = () => {
  if (!props.currentShareCode) {
    message.warning('请先选择一个分享代码');
    return;
  }

  client.message
    .getMessages(props.currentShareCode)
    .then((response) => {
      if (response.data) {
        messageList.value = response.data
          .filter((msg) => msg.content && msg.createdAt && msg.id)
          .map((msg) => ({
            id: msg.id ?? -1,
            content: msg.content ?? '',
            timestamp: msg.createdAt ?? '',
          }));
      } else {
        message.error('加载消息失败，请稍后重试');
      }
    })
    .catch((error) => {
      console.error('加载消息失败:', error);
      message.error('加载消息失败，请稍后重试');
    });
};
// 初始化消息列表
watch(() => props.currentShareCode, pullMessages);

// 格式化时间戳
const formatTimestamp = (time?: string) => {
  if (!time) {
    return '';
  }
  const now = new Date(time);
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
};

// 添加新消息
const addMessage = async () => {
  const content = newMessageContent.value.trim();
  if (!content) {
    message.warning('请输入消息内容');
    return;
  }
  if (!props.currentShareCode) {
    message.warning('请先选择一个分享');
    return;
  }
  if (!props.currentEditToken) {
    message.error('缺少编辑令牌，无法添加消息。请确保您有权限编辑此分享。');
    return;
  }

  try {
    const { data } = await client.message.addMessageV2(
      props.currentShareCode,
      props.currentEditToken,
      { message: content },
    );
    if (data) {
      messageList.value.push(data);
      newMessageContent.value = '';
      message.success('消息添加成功');
      pullMessages(); // 刷新消息列表
    } else {
      message.error('添加消息失败，请稍后重试');
    }
  } catch (error) {
    console.error('添加消息失败:', error);
    message.error('添加消息失败，请稍后重试');
  }
};

// 删除消息
const deleteMessage = async (msg: MessageItem) => {
  if (!props.currentShareCode) {
    message.warning('请先选择一个分享');
    return;
  }
  if (!props.currentEditToken) {
    message.error('缺少编辑令牌，无法删除消息。请确保您有权限编辑此分享。');
    return;
  }
  if (!msg.id) {
    message.error('无法删除未保存的消息');
    return;
  }

  try {
    const { data } = await client.message.deleteMessage(
      props.currentShareCode,
      props.currentEditToken,
      msg.id,
    );
    if (data) {
      messageList.value = messageList.value.filter((m) => m.id !== msg.id);
      message.success('消息删除成功');
      pullMessages(); // 刷新消息列表
    } else {
      message.error('删除消息失败，请稍后重试');
    }
  } catch (error) {
    console.error('删除消息失败:', error);
    message.error('删除消息失败，请稍后重试');
  }
};

// 关闭对话框
const closeDialog = () => {
  isVisible.value = false;
};

// 处理输入框回车事件
const handleInputKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && event.ctrlKey) {
    event.preventDefault();
    addMessage();
  }
};
</script>

<template>
  <Dialog
    v-model="isVisible"
    type="modal"
    aria-labelledby="message-dialog-title"
  >
    <DialogBody>
      <div class="mx-auto w-full">
        <!-- 对话框标题 -->
        <div class="mb-6 flex items-center justify-between">
          <div class="flex items-center gap-3">
            <div class="rounded-lg bg-orange-100 p-2 dark:bg-orange-900/30">
              <svg
                class="h-6 w-6 text-orange-600 dark:text-orange-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                />
              </svg>
            </div>
            <div>
              <h2
                id="message-dialog-title"
                class="text-xl font-semibold text-gray-900 dark:text-gray-100"
              >
                消息管理
              </h2>
              <p class="text-sm text-gray-600 dark:text-gray-300">
                管理分享的所有消息，可以添加新消息或删除现有消息
              </p>
            </div>
          </div>
          <Button appearance="subtle" icon-only @click="closeDialog">
            <Close />
          </Button>
        </div>

        <!-- 权限警告提示 -->
        <div
          v-if="!currentEditToken"
          class="mb-4 rounded-md border border-yellow-200 bg-yellow-50 p-3 dark:border-yellow-800 dark:bg-yellow-900/10"
        >
          <div class="flex">
            <div class="flex-shrink-0">
              <svg
                class="h-5 w-5 text-yellow-400"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fill-rule="evenodd"
                  d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                  clip-rule="evenodd"
                />
              </svg>
            </div>
            <div class="ml-3">
              <h3
                class="text-sm font-medium text-yellow-800 dark:text-yellow-200"
              >
                只读模式
              </h3>
              <p class="mt-1 text-sm text-yellow-700 dark:text-yellow-300">
                缺少编辑权限，您只能查看消息，无法添加或删除消息。
              </p>
            </div>
          </div>
        </div>

        <!-- 消息列表标题 -->
        <div class="mb-4">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
            所有消息
          </h3>
        </div>

        <!-- 消息列表内容 -->
        <div class="mb-6 max-h-60 overflow-y-auto">
          <!-- 空状态 -->
          <div v-if="messageList.length === 0" class="py-8 text-center">
            <div class="mb-4">
              <svg
                class="mx-auto h-16 w-16 text-gray-400 dark:text-gray-500"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="1"
                  d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                />
              </svg>
            </div>
            <p
              class="mb-2 text-lg font-medium text-gray-900 dark:text-gray-100"
            >
              暂无消息
            </p>
            <p class="text-sm text-gray-600 dark:text-gray-300">
              在下方添加第一条消息
            </p>
          </div>

          <!-- 消息列表 -->
          <div v-else class="space-y-3">
            <div
              v-for="msg in messageList"
              :key="msg.id"
              class="rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800"
            >
              <div class="flex items-start justify-between">
                <div class="min-w-0 flex-1">
                  <p
                    class="break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    "{{ msg.content }}"
                  </p>
                  <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {{ formatTimestamp(msg.createdAt) }}
                  </p>
                </div>
                <Button
                  appearance="subtle"
                  icon-only
                  size="small"
                  @click="deleteMessage(msg)"
                  :disabled="!currentEditToken"
                  class="ml-2 text-red-600 hover:bg-red-50 hover:text-red-700 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-red-900/20"
                >
                  <Delete theme="outline" size="14" />
                </Button>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加新消息输入区域 -->
        <div class="pb-1">
          <div class="flex gap-3">
            <div class="flex-1">
              <div>
                <TextArea
                  auto-resize
                  block
                  v-model="newMessageContent"
                  placeholder="输入新消息内容..."
                  :disabled="!currentEditToken"
                  @keydown="handleInputKeydown"
                />
              </div>
            </div>
            <Button
              appearance="primary"
              @click="addMessage"
              :disabled="!newMessageContent.trim() || !currentEditToken"
            >
              <div class="flex items-center gap-2">
                <svg
                  class="h-4 w-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                  />
                </svg>
                <span>添加</span>
              </div>
            </Button>
          </div>
        </div>
      </div>
    </DialogBody>
  </Dialog>
</template>

<style scoped>
/* 自定义滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: rgb(156 163 175 / 50%);
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background-color: rgb(156 163 175 / 70%);
}

.dark .overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: rgb(75 85 99 / 50%);
}

.dark .overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background-color: rgb(75 85 99 / 70%);
}
</style>
